package com.zerosoft.javagui;
import ch.qos.logback.classic.spi.EventArgUtil;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Pos;
import javafx.geometry.Rectangle2D;
import javafx.scene.control.Button;
import javafx.scene.image.ImageView;
import javafx.scene.image.PixelBuffer;
import javafx.scene.image.PixelFormat;
import javafx.scene.image.WritableImage;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.stage.StageStyle;
import uk.co.caprica.vlcj.factory.MediaPlayerFactory;
import uk.co.caprica.vlcj.player.base.MediaPlayer;
import uk.co.caprica.vlcj.player.component.EmbeddedMediaPlayerComponent;
import uk.co.caprica.vlcj.player.embedded.EmbeddedMediaPlayer;

import uk.co.caprica.vlcj.player.embedded.videosurface.CallbackVideoSurface;
import uk.co.caprica.vlcj.player.embedded.videosurface.VideoSurfaceAdapters;
import uk.co.caprica.vlcj.player.embedded.videosurface.callback.BufferFormat;
import uk.co.caprica.vlcj.player.embedded.videosurface.callback.BufferFormatCallback;
import uk.co.caprica.vlcj.player.embedded.videosurface.callback.RenderCallback;
import uk.co.caprica.vlcj.player.embedded.videosurface.callback.format.RV32BufferFormat;

import java.nio.ByteBuffer;
import java.util.Stack;


public class MainApp extends Application {
    private MediaPlayerFactory mediaPlayerFactory;
    private EmbeddedMediaPlayer embeddedMediaPlayer;

    private WritableImage videoImage;
    private PixelBuffer<ByteBuffer> videoPixelBuffer;
    private ImageView videoImageView;

    private boolean fullScreen;

    @Override
    public void init() throws Exception {
        super.init();
        mediaPlayerFactory = new MediaPlayerFactory();
        embeddedMediaPlayer = mediaPlayerFactory.mediaPlayers().newEmbeddedMediaPlayer();
        embeddedMediaPlayer.videoSurface().set(new FXCallbackVideoSurface());

        fullScreen = false;
    }
    @Override
    public void start(Stage stage) throws Exception {
        StackPane root = new StackPane();
        root.setStyle("-fx-background-color: black;");
        videoImageView = new ImageView();
        videoImageView.setPreserveRatio(true);
        videoImageView.fitWidthProperty().bind(root.widthProperty());
        videoImageView.fitHeightProperty().bind(root.heightProperty());
//        root.getChildren().add(videoImageView);
        videoImageView.setOnMouseClicked(e -> {
            System.out.printf("click");
        });
//        setMedia("rtsp://admin:hik12345@192.168.31.25:554/streaming/channels/1");
        setMedia("/Users/guxuefeng/Downloads/反诈短剧-黑喵警长.mp4");



        Button btn = new Button("全屏");
        btn.setStyle("-fx-background-color: #FF9933;");
        btn.alignmentProperty().set(Pos.BOTTOM_CENTER);
        btn.setOnAction(e -> {
            System.out.println(e.toString());
            fullScreen = !fullScreen;
            stage.setFullScreen(fullScreen);
            embeddedMediaPlayer.fullScreen().toggle();
        });
        HBox box = new HBox();
        box.setStyle("-fx-background-color: black;");
        box.setAlignment(Pos.BOTTOM_CENTER);
        box.setPrefHeight(50);
        box.setPrefWidth(800);
        box.setSpacing(10);
        box.getChildren().add(btn);

        root.getChildren().add(box);
        root.getChildren().add(videoImageView);

        Scene scene = new Scene(root, 800, 600);
        stage.setScene(scene);
//        stage.initStyle(StageStyle.TRANSPARENT);
        stage.setTitle("JavaFX 与 VLC 集成示例");
//        stage.setIconified(true);
        stage.show();

//        Parent root = FXMLLoader.load(getClass().getResource("MainView.fxml"));
//        Button btn = new Button("Hello World");
//        btn.setOnAction(e -> System.out.println("Hello World"));

//        mediaPlayerComponent = new EmbeddedMediaPlayerComponent();
//
//        // 创建一个边界面板
//        BorderPane borderPane = new BorderPane();
////        stackPane.getChildren().add(mediaPlayerComponent);
//
//        // 将媒体播放器组件添加到边界面板的中心
//        borderPane.setCenter(mediaPlayerComponent);
//
//        // 创建一个场景，设置宽和高
//        Scene scene = new Scene(borderPane, 800, 600);
//
//        // 设置场景和标题
//        stage.setScene(scene);
//        stage.setTitle("JavaFX 与 VLC 集成示例");
//        stage.show();
//
//        // 播放媒体文件
//        mediaPlayerComponent.mediaPlayer().media().play("rtsp://admin:hik12345@192.168.31.25:554/streaming/channels/1"); // 替换为你的文件路径

//        MediaPlayerFactory mediaPlayerFactory = new MediaPlayerFactory();
//        EmbeddedMediaPlayer mediaPlayer = mediaPlayerFactory.mediaPlayers().newEmbeddedMediaPlayer();
////        EmbeddedMediaPlayer embeddedMediaPlayer = mediaPlayerFactory.newEmbeddedMediaPlayer();
//
//
//        // RTSP流地址
//        String rtspUrl = "rtsp://admin:hik12345@192.168.31.25:554/streaming/channels/1";
//        mediaPlayer.media().play(rtspUrl);
//        try{
//            System.out.println("rtspUrl:"+rtspUrl);
//            Media media = new Media(mediaPlayer1.mrlToURI(rtspUrl));
//            MediaPlayer mediaPlayer = new MediaPlayer(media);
//            MediaView mediaView = new MediaView(mediaPlayer);
//            StackPane root = new StackPane();
//        root.getChildren().add(btn);
//            root.getChildren().add(mediaView);
//            stage.setTitle("JavaFX");
//            stage.setScene(new Scene(root, 600, 400));
//
//            stage.show();
//        }
//        catch (Exception e){
//            System.out.println("rtspUrl:"+rtspUrl);
//        }

    }

    @Override
    public final void stop() throws Exception {
        embeddedMediaPlayer.controls().stop();
        embeddedMediaPlayer.release();
        mediaPlayerFactory.release();
    }

    private class FXCallbackVideoSurface extends CallbackVideoSurface {
        FXCallbackVideoSurface() {
            super(new FXBufferFormatCallback(), new FXRenderCallback(), true, VideoSurfaceAdapters.getVideoSurfaceAdapter());
        }
    }

    private class FXBufferFormatCallback implements BufferFormatCallback {
        private int sourceWidth;
        private int sourceHeight;

        @Override
        public BufferFormat getBufferFormat(int sourceWidth, int sourceHeight) {
            this.sourceWidth = sourceWidth;
            this.sourceHeight = sourceHeight;
            return new RV32BufferFormat(sourceWidth, sourceHeight);
        }


        @Override
        public void allocatedBuffers(ByteBuffer[] buffers) {
            assert buffers[0].capacity() == sourceWidth * sourceHeight * 4;
            PixelFormat<ByteBuffer> pixelFormat = PixelFormat.getByteBgraPreInstance();
            videoPixelBuffer = new PixelBuffer<>(sourceWidth, sourceHeight, buffers[0], pixelFormat);
            videoImage = new WritableImage(videoPixelBuffer);
            videoImageView.setImage(videoImage);
        }
    }

    private class FXRenderCallback implements RenderCallback {
        @Override
        public void display(MediaPlayer mediaPlayer, ByteBuffer[] nativeBuffers, BufferFormat bufferFormat) {
            Platform.runLater(() -> {
                videoPixelBuffer.updateBuffer(pb -> null);
            });
        }
    }

    public void setMedia(String path) {
        embeddedMediaPlayer.media().play(path
//                , ":no-audio"
                , ":rtsp=tcp"
                , ":codec=ffmpeg"
                , ":vout=any"
                , ":avcodec-threads=1"
                , ":avcodec-hw=any"
                , ":network-caching=200"
                , ":prefetch-buffer-size=1024"
                , ":prefetch-read-size=65535"
                , ":file-caching=1000"
        );
        //循环播放
        embeddedMediaPlayer.controls().setRepeat(true);
    }


    public static void main(String[] args) {
        launch(args);
    }
}
